package com.ycMc.controller;

import com.ycMc.bean.request.OrderDetailRequest;
import com.ycMc.bean.request.OrderRequest;
import com.ycMc.bean.response.ChartResponse;
import com.ycMc.bean.response.ListResponse;
import com.ycMc.bean.response.ObjectResponse;
import com.ycMc.bean.response.PageBeanResponse;
import com.ycMc.common.bean.PageBean;
import com.ycMc.common.bean.Request;
import com.ycMc.common.bean.Response;
import com.ycMc.constant.ExcelPoiUtil;
import com.ycMc.constant.OrderStateConstant;
import com.ycMc.domain.Order;
import com.ycMc.domain.OrderDetail;
import com.ycMc.domain.User;
import com.ycMc.service.OrderService;
import com.ycMc.utils.BaseUtils;
import com.ycMc.utils.DateUtil;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * Created by libo2 on 2017/8/23.
 */
@RequestMapping("api/order")
@Controller
public class OrderController{

    @Autowired
    private OrderService orderService;


    @RequestMapping("insert")
    @ResponseBody
    /**
    *Create by libo2
    *Time:2017/9/3 on 0:41
    *@Request :[request, httpServletRequest]
    *@Response:com.ycMc.common.bean.Response
     * 添加一个订单，orderId，以及createTime 不需要传递
     * 其他参数 见orderRequest 对象
    **/
    public Response insert(OrderRequest request){
        Response response = new Response();
     try {
         Order order = new Order();
         BeanUtils.copyProperties(request,order);
         response.setStatusCode(Response.SUCCESS);
         response.setMsg("success");
        orderService.insert(order);
     }
     catch (Exception e){
         response.setStatusCode(Response.FAILED);
         response.setMsg(e.getMessage());
         e.printStackTrace();
     }
        return  response;
    }

    @RequestMapping("update")
    @ResponseBody
    /**
    *Create by libo2
    *Time:2017/9/3 on 0:42
    *@Request :[request]
    *@Response:com.ycMc.common.bean.Response
     * 通用修改 通过orderId 修改
    **/
    public Response update(OrderRequest request){
        Response response = new Response();
        try {
            Order order = new Order();
            BeanUtils.copyProperties(request, order);
            orderService.update(order);
            response.setStatusCode(Response.SUCCESS);
            response.setMsg("success");
        }
        catch (Exception e){
            response.setStatusCode(Response.FAILED);
            response.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return  response;
    }


    @RequestMapping("updateOrderDetail")
    @ResponseBody
    /**
     *Create by libo2
     *Time:2017/9/3 on 0:42
     *@Request :[request]
     *@Response:com.ycMc.common.bean.Response
     * 通用修改 通过orderId 修改
     **/
    public Response updateOrderDetail(OrderDetailRequest request){
        Response response = new Response();
        try {

            orderService.updateOrderDetail(request);
            response.setStatusCode(Response.SUCCESS);
            response.setMsg("success");
        }
        catch (Exception e){
            response.setStatusCode(Response.FAILED);
            response.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return  response;
    }


    @RequestMapping("updateOrderFare")
    @ResponseBody
    /**
     *Create by libo2
     *Time:2017/9/3 on 0:42
     *@Request :[request]
     *@Response:com.ycMc.common.bean.Response
     * 通用修改 通过orderId 修改
     **/
    public Response updateOrderFare(OrderRequest request){
        Response response = new Response();
        try {
            Order order = new Order();
            order.setOrderState(request.getOrderState());
            order.setFareStatus(request.getFareStatus());
            order.setFareType(request.getFareType());
            order.setFareTime(System.currentTimeMillis());
            order.setOrderId(request.getOrderId());
            orderService.update(order);
            response.setStatusCode(Response.SUCCESS);
            response.setMsg("success");
        }
        catch (Exception e){
            response.setStatusCode(Response.FAILED);
            response.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return  response;
    }

    @RequestMapping("delete")
    @ResponseBody
    /**
    *Create by libo2
    *Time:2017/9/3 on 0:42
    *@Request :[request]
    *@Response:com.ycMc.common.bean.Response
     * 通过orderId 删除
    **/
    public Response delete(OrderRequest request){
        Response response = new Response();
        try {
            orderService.delete(request.getOrderId());
            response.setStatusCode(Response.SUCCESS);
            response.setMsg("success");
        }
        catch (Exception e){
            response.setStatusCode(Response.FAILED);
            response.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return  response;
    }



    @RequestMapping("selectByUserId")
    @ResponseBody
    /**
    *Create by libo2
    *Time:2017/9/3 on 0:43
    *@Request :[request, httpServletRequest]
    *@Response:com.ycMc.bean.response.ListResponse
     * 通过userId 传递对象
    **/
    public ListResponse selectByUserId(OrderRequest request){
        ListResponse response = new ListResponse();
        try {

                response.setCommonList(orderService.selectByUserId(request.getUserId()));
            response.setStatusCode(Response.SUCCESS);
            response.setMsg("success");

        }
        catch (Exception e){
            response.setStatusCode(Response.FAILED);
            response.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return  response;
    }

    @RequestMapping("selectAll")
    @ResponseBody
    /**
    *Create by libo2
    *Time:2017/9/3 on 0:44
    *@Request :[]
    *@Response:com.ycMc.bean.response.ListResponse
     * 查询所有
    **/
    public ListResponse selectAll (Request request){
        ListResponse response = new ListResponse();
        try {
            response.setCommonList(orderService.selectAll());
            response.setStatusCode(Response.SUCCESS);
            response.setMsg("success");
        }
        catch (Exception e){
            response.setStatusCode(Response.FAILED);
            response.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return  response;
    }


    @RequestMapping("selectOne")
    @ResponseBody
    /**
    *Create by libo2
    *Time:2017/9/3 on 0:44
    *@Request :[request]
    *@Response:com.ycMc.bean.response.ObjectResponse
     * 通过orderId 查一
    **/
    public ObjectResponse selectOne (OrderRequest request){
        ObjectResponse response = new ObjectResponse();
        try {
                response.setObject(orderService.selectOne(request.getOrderId()));
            response.setStatusCode(Response.SUCCESS);
            response.setMsg("success");
        }
        catch (Exception e){
            response.setStatusCode(Response.FAILED);
            response.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return  response;
    }
    @RequestMapping("select")
    @ResponseBody
    /**
     *Create by libo2
     *Time:2017/9/3 on 0:44
     *@Request :[]
     *@Response:com.ycMc.bean.response.ListResponse
     * 查询所有
     **/
    public ListResponse select (OrderRequest request){
        ListResponse response = new ListResponse();
        try {
            Order order = new Order();
            BeanUtils.copyProperties(request,order);
            response.setCommonList(orderService.select(order));
            response.setStatusCode(Response.SUCCESS);
            response.setMsg("success");
        }
        catch (Exception e){
            response.setStatusCode(Response.FAILED);
            response.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return  response;
    }




    @RequestMapping(value = "query",method = RequestMethod.POST)
    @ResponseBody
    /**
     *Create by libo2
     *Time:2017/9/3 on 0:44
     *@Request :[]
     *@Response:com.ycMc.bean.response.ListResponse
     * 查询所有
     **/
    public PageBeanResponse query(OrderRequest request){
        PageBeanResponse response = new PageBeanResponse();
        try {
            PageBean pageBean = orderService.query(request.getSelectedUserId(),request.getCurrentPage(),request.getPageSize(),request.getOrderState(),request.getTaxStatus(),request.getStartTime(),request.getEndTime(),request.getOrderId(),request.getShoppingAddress(),request.getUserPhone(),request.getRealName());
            response.setPageBean(pageBean);
            response.setStatusCode(Response.SUCCESS);
            response.setMsg("success");
        }
        catch (Exception e){
            response.setStatusCode(Response.FAILED);
            response.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return  response;
    }





    @RequestMapping("selectOrderDetailByOrderId")
    @ResponseBody
    /**
    *Create by libo2
    *Time:2017/9/24 on 0:06
    *@Request :[request]
    *@Response:com.ycMc.bean.response.ListResponse
     * 通过订单获取订单详情
    **/
    public ListResponse selectOrderDetailByOrderId (OrderRequest request){
        ListResponse response = new ListResponse();
        try {
            response.setCommonList(orderService.selectOrderDetailByOrderId(request.getOrderId()));
            response.setStatusCode(Response.SUCCESS);
            response.setMsg("success");
        }
        catch (Exception e){
            response.setStatusCode(Response.FAILED);
            response.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return  response;
    }


    /**
    *Create by libo2
    *Time:2017/9/23 on 10:50
    *@Request :
    *@Response:通过商品Id 来开单
    **/
    @RequestMapping("insertOrdersByProductIds")
    @ResponseBody
    public Response insertOrdersByProductIds(OrderDetailRequest request,HttpServletRequest httpServletRequest){
        Response response = new Response();

        try{
            response = orderService.insertOrdersByProductIds(request,(User)httpServletRequest.getSession().getAttribute("user"));
        }
        catch (RuntimeException e) {
            response.setStatusCode(Response.SUCCESS);
            response.setMsg("商品库存不足，下单失败");
            e.printStackTrace();
        }


        return  response;
    }



    /**
    *Create by libo2
    *Time:2017/9/16 on 20:11
    *@Request :
    *@Response:
     * 根据品牌，
     * 统计订单 销售数量
    **/
    @RequestMapping("getChartByProductBrand")
    @ResponseBody
    public ChartResponse getChartByProductBrand(Request request,HttpServletRequest httpServletRequest){
        User user = (User)httpServletRequest.getSession().getAttribute("user");
        ChartResponse response = orderService.getChartByProductBrand(user);
        return  response;
    }

    @RequestMapping("getChartByProductId")
    @ResponseBody
    public ChartResponse getChartByProductId(Request request,HttpServletRequest httpServletRequest){
        User user = (User)httpServletRequest.getSession().getAttribute("user");
        ChartResponse response = orderService.getChartByProductId(user);
        return  response;
    }

    @RequestMapping("getChartByTimeYears")
    @ResponseBody
    public ChartResponse getChartByTimeYears(Request request,HttpServletRequest httpServletRequest){
        User user = (User)httpServletRequest.getSession().getAttribute("user");
        ChartResponse response = orderService.getChartByYears(user);
        return  response;
    }

    @RequestMapping("getChartByTimeMonths")
    @ResponseBody
    public ChartResponse getChartByTimeMonths(Request request,HttpServletRequest httpServletRequest){
        User user = (User)httpServletRequest.getSession().getAttribute("user");
        ChartResponse response = orderService.getChartByMonths(user);
        return  response;
    }

    @RequestMapping("getChartByTimeDays")
    @ResponseBody
    public ChartResponse getChartByTimeDays(Request request,HttpServletRequest httpServletRequest){
        User user = (User)httpServletRequest.getSession().getAttribute("user");
        ChartResponse response = orderService.getChartByDays(user);
        return  response;
    }



    /**
    *Create by libo2
    *Time:2017/10/16 on 21:21
    *@Request :
    *@Response:导出excel表返回下载链接
    **/
    @RequestMapping("downloadOrderUserMessage")
    @ResponseBody
    public Response downloadOrderUserMessage(OrderRequest request,HttpServletRequest httpServletRequest){
        Response  response = new Response();


        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("学生表一");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCell cell = row.createCell(0);

        List<Order> orders =  orderService.selectAll();

        cell.setCellValue("序号");
        cell.setCellStyle(style);
        cell = row.createCell(1);
        cell.setCellValue("用户名称");
        cell.setCellStyle(style);
        cell = row.createCell(2);
        cell.setCellValue("用户地址");
        cell.setCellStyle(style);
        cell = row.createCell(3);
        cell.setCellValue("用户联系方式");
        cell.setCellStyle(style);
        int i =0;
        for(Order order:orders){
            row = sheet.createRow((int) i + 1);
            row.createCell(0).setCellValue(i);
            row.createCell(1).setCellValue(order.getRealName());
            row.createCell(2).setCellValue(order.getShoppingAddress());
            row.createCell(3).setCellValue(order.getUserPhone());
            i++;
        }
        try
        {
            String fileName = "UserMessage"+DateUtil.dateFormat2(System.currentTimeMillis())+".xls";

            String fileNameUrl = ExcelPoiUtil.Linux_url+fileName;
            String downloadUrl = "excelData/"+fileName;
            FileOutputStream fout = new FileOutputStream(fileNameUrl);
            wb.write(fout);
            fout.close();
            response.setStatusCode(Response.SUCCESS);
            response.setMsg(downloadUrl);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return response;
    }



    /**
     *Create by libo2
     *Time:2017/10/16 on 21:21
     *@Request :
     *@Response:根据筛选条件导出订单表
     **/
    @RequestMapping("downloadOrderByQueryCondition")
    @ResponseBody
    public Response downloadOrderByQueryCondition(OrderRequest request){
        Response  response = new Response();


        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("订单记录表");
        sheet.setColumnWidth(1, 15 * 256);
        sheet.setColumnWidth(2, 8 * 256);
        sheet.setColumnWidth(3, 4 * 256);
        sheet.setColumnWidth(4, 18 * 256);
        sheet.setColumnWidth(5, 18 * 256);
        sheet.setColumnWidth(6, 18 * 256);
        sheet.setColumnWidth(7, 18 * 256);
        sheet.setColumnWidth(8, 18 * 256);
        sheet.setColumnWidth(9, 18 * 256);
        sheet.setColumnWidth(10, 18 * 256);
        sheet.setColumnWidth(11, 14 * 256);
        sheet.setColumnWidth(12, 14 * 256);
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 创建一个居中格式


        HSSFCell cell = row.createCell(0);

        PageBean pageBean = orderService.query(request.getSelectedUserId(),request.getCurrentPage(),request.getPageSize(),request.getOrderState(),request.getTaxStatus(),request.getStartTime(),request.getEndTime(),request.getOrderId(),request.getShoppingAddress(),request.getUserPhone(),request.getRealName());

        List<Order> orders =  pageBean.getList();

        cell.setCellValue("序号");
        cell.setCellStyle(style);
        cell = row.createCell(1);
        cell.setCellValue("订单编号");
        cell.setCellStyle(style);
        cell = row.createCell(2);
        cell.setCellValue("用户编号");
        cell.setCellStyle(style);
        cell = row.createCell(3);
        cell.setCellValue("订单状态");
        cell.setCellStyle(style);
        cell = row.createCell(4);
        cell.setCellValue("收货地址信息");
        cell.setCellStyle(style);
        cell = row.createCell(5);
        cell.setCellValue("创建时间");
        cell.setCellStyle(style);
        cell = row.createCell(6);
        cell.setCellValue("完成时间");
        cell.setCellStyle(style);
        cell = row.createCell(7);
        cell.setCellValue("总数量");
        cell.setCellStyle(style);
        cell = row.createCell(8);
        cell.setCellValue("总价格");
        cell.setCellStyle(style);
        cell = row.createCell(9);
        cell.setCellValue("用户联系方式");
        cell.setCellStyle(style);
        cell = row.createCell(10);
        cell.setCellValue("用户真实姓名");
        cell.setCellStyle(style);
        cell = row.createCell(11);
        cell.setCellValue("是否开票");
        cell.setCellStyle(style);
        cell = row.createCell(12);
        cell.setCellValue("发票号");
        cell.setCellStyle(style);
        cell = row.createCell(13);
        cell.setCellValue("开票金额");
        cell.setCellStyle(style);
        cell = row.createCell(14);
        cell.setCellValue("物流方式");
        cell.setCellStyle(style);
        cell = row.createCell(15);
        cell.setCellValue("物流状态");
        cell.setCellStyle(style);
        cell = row.createCell(16);
        cell.setCellValue("发货时间");
        cell.setCellStyle(style);
        cell = row.createCell(17);
        cell.setCellValue("订单备注");
        cell.setCellStyle(style);



        int i =1;
        for(Order order:orders){
            row = sheet.createRow((int) i );
            row.createCell(0).setCellValue(i);
            row.createCell(1).setCellValue(order.getOrderId());
            row.createCell(2).setCellValue(order.getUserId());
            if(order.getOrderState()== OrderStateConstant.ORDER_STATE__FINISH){
                row.createCell(3).setCellValue("订单已完成");
            }
            else if(order.getOrderState()==OrderStateConstant.ORDER_STATE_NO_CONFIRM){
                row.createCell(3).setCellValue("订单未确认");
            }
            else if(order.getOrderState()==OrderStateConstant.ORDER_STATE_NO_DELIVER){
                row.createCell(3).setCellValue("订单未发货");
            }
            else if(order.getOrderState()==OrderStateConstant.ORDER_STATE_NO_PAYMENT){
                row.createCell(3).setCellValue("订单未支付");
            }

            row.createCell(4).setCellValue(order.getShoppingAddress());
            row.createCell(5).setCellValue(DateUtil.dateFormat3(order.getCreateTime()));
            row.createCell(6).setCellValue(DateUtil.dateFormat3(order.getPayTime()));
            row.createCell(7).setCellValue(order.getNumber());
            row.createCell(8).setCellValue(order.getTotalPrice());
            row.createCell(9).setCellValue(order.getUserPhone());
            row.createCell(10).setCellValue(order.getRealName());
            if(order.getTaxStatus()==1){
                row.createCell(11).setCellValue("已开发票");
            }else{
                row.createCell(11).setCellValue("未开发票");
            }

            row.createCell(12).setCellValue(order.getTaxNumber());
            row.createCell(13).setCellValue(order.getTaxMoney());
            row.createCell(14).setCellValue(order.getFareType());
            if(order.getFareStatus()==1){
                row.createCell(15).setCellValue("已发货");
            }else{
                row.createCell(15).setCellValue("未发货");
            }
            row.createCell(16).setCellValue(DateUtil.dateFormat3(order.getFareTime()));
            row.createCell(17).setCellValue(order.getOrderRemark());

            i++;

            List<OrderDetail> orderDetailList = orderService.selectOrderDetailByOrderId(order.getOrderId());

            row = sheet.createRow((int) i );
            int z=0;
            cell = row.createCell(3+z);
            cell.setCellValue("序号");
            cell = row.createCell(4+z);
            cell.setCellValue("订单详情编号");
            cell = row.createCell(5+z);
            cell.setCellValue("产品名称");
            cell = row.createCell(6+z);
            cell.setCellValue("产品品牌");
            cell = row.createCell(7+z);
            cell.setCellValue("产品型号");
            cell = row.createCell(8+z);
            cell.setCellValue("产品编号");
            cell = row.createCell(9 +z);
            cell.setCellValue("用户编号");
            cell = row.createCell(10+z);
            cell.setCellValue("购买单价");
            cell = row.createCell(11+z);
            cell.setCellValue("购买数量");
            cell = row.createCell(12+z);
            cell.setCellValue("订单总价");

            i++;
            int h = 1;
            for(OrderDetail orderDetail :orderDetailList){
                row = sheet.createRow((int) i );
                cell = row.createCell(3+z);
                cell.setCellValue(h);
                cell = row.createCell(4+z);
                cell.setCellValue(orderDetail.getOrderDetailId());
                cell = row.createCell(5+z);
                cell.setCellValue(orderDetail.getProductName());
                cell = row.createCell(6+z);
                cell.setCellValue(orderDetail.getProductBrand());
                cell = row.createCell(7+z);
                cell.setCellValue(orderDetail.getProductVersion());
                cell = row.createCell(8+z);
                cell.setCellValue(orderDetail.getProductId());
                cell = row.createCell(9+z);
                cell.setCellValue(orderDetail.getUserId());
                cell = row.createCell(10+z);
                cell.setCellValue(orderDetail.getSinglePrice());
                cell = row.createCell(11+z);
                cell.setCellValue(orderDetail.getNumber());
                cell = row.createCell(12+z);
                cell.setCellValue(orderDetail.getSinglePrice()*orderDetail.getNumber());

                i++;
                h++;
            }


        }
        try
        {
            String fileName = "OrderExcel"+DateUtil.dateFormat2(System.currentTimeMillis())+".xls";
            String fileNameUrl = ExcelPoiUtil.Linux_url+fileName;
            FileOutputStream fout = new FileOutputStream(fileNameUrl);
            wb.write(fout);
            fout.close();
            response.setMsg("excelData/" + fileName);
            response.setStatusCode(Response.SUCCESS);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return response;
    }





}
